using Newtonsoft.Json;
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Hotel.UI.Common
{
	/// <summary>
	/// 网页抓取辅助类
	/// </summary>
	public class HttpWebRequestHelper
    {  // Post请求
        public string PostResponse(string url, string postData, out string statusCode)
        {
            string result = string.Empty;
            //设置Http的正文
            HttpContent httpContent = new StringContent(postData);
            //设置Http的内容标头
            httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            //设置Http的内容标头的字符
            httpContent.Headers.ContentType.CharSet = "utf-8";
            using (HttpClient httpClient = new HttpClient())
            {
                //异步Post
                HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
                //输出Http响应状态码
                statusCode = response.StatusCode.ToString();
                //确保Http响应成功
                if (response.IsSuccessStatusCode)
                {
                    //异步读取json
                    result = response.Content.ReadAsStringAsync().Result;
                }
            }
            return result;
        }

        // 泛型：Post请求
        public T PostResponse<T>(string url, string postData) where T : class, new()
        {
            T result = default(T);

            HttpContent httpContent = new StringContent(postData);
            httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            httpContent.Headers.ContentType.CharSet = "utf-8";
            using (HttpClient httpClient = new HttpClient())
            {
                HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

                if (response.IsSuccessStatusCode)
                {
                    Task<string> t = response.Content.ReadAsStringAsync();
                    string s = t.Result;
                    //Newtonsoft.Json
                    string json = JsonConvert.DeserializeObject(s).ToString();
                    result = JsonConvert.DeserializeObject<T>(json);
                }
            }
            return result;
        }

        // 泛型：Get请求
        public T GetResponse<T>(string url) where T : class, new()
        {
            T result = default(T);

            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = httpClient.GetAsync(url).Result;

                if (response.IsSuccessStatusCode)
                {
                    Task<string> t = response.Content.ReadAsStringAsync();
                    string s = t.Result;
                    string json = JsonConvert.DeserializeObject(s).ToString();
                    result = JsonConvert.DeserializeObject<T>(json);
                }
            }
            return result;
        }

        // Get请求
        public string GetResponse(string url, out string statusCode)
        {
            string result = string.Empty;

            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = httpClient.GetAsync(url).Result;
                statusCode = response.StatusCode.ToString();

                if (response.IsSuccessStatusCode)
                {
                    result = response.Content.ReadAsStringAsync().Result;
                }
            }
            return result;
        }

        // Put请求
        public string PutResponse(string url, string putData, out string statusCode)
        {
            string result = string.Empty;
            HttpContent httpContent = new StringContent(putData);
            httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            httpContent.Headers.ContentType.CharSet = "utf-8";
            using (HttpClient httpClient = new HttpClient())
            {
                HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result;
                statusCode = response.StatusCode.ToString();
                if (response.IsSuccessStatusCode)
                {
                    result = response.Content.ReadAsStringAsync().Result;
                }
            }
            return result;
        }

        // 泛型：Put请求
        public T PutResponse<T>(string url, string putData) where T : class, new()
        {
            T result = default(T);
            HttpContent httpContent = new StringContent(putData);
            httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            httpContent.Headers.ContentType.CharSet = "utf-8";
            using (HttpClient httpClient = new HttpClient())
            {
                HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result;

                if (response.IsSuccessStatusCode)
                {
                    Task<string> t = response.Content.ReadAsStringAsync();
                    string s = t.Result;
                    string json = JsonConvert.DeserializeObject(s).ToString();
                    result = JsonConvert.DeserializeObject<T>(json);
                }
            }
            return result;
        }

        private CookieContainer cookieContainer_0;

		/// <summary>
		/// </summary>
		/// <param name="cookie"></param>
		public HttpWebRequestHelper(CookieContainer cookie)
		{
			
			
			this.cookieContainer_0 = cookie;
		}

		/// <summary>
		/// </summary>
		public HttpWebRequestHelper()
		{
			
			
			this.cookieContainer_0 = new CookieContainer();
		}

		/// <summary>
		/// 获取页面html   encodingname:gb2312
		/// </summary>
		/// <param name="uri">访问url</param>
		/// <returns></returns>
		public string Get(string uri)
		{
			return this.Get(uri, uri, "gb2312");
		}

		/// <summary>
		/// 获取页面html   encodingname:gb2312
		/// </summary>
		/// <param name="uri">访问url</param>
		/// <param name="refererUri">来源url</param>
		/// <returns></returns>
		public string Get(string uri, string refererUri)
		{
			return this.Get(uri, refererUri, "gb2312");
		}

		/// <summary>
		/// 获取页面html
		/// </summary>
		/// <param name="uri">访问url</param>
		/// <param name="refererUri">来源url</param>
		/// <param name="encodingName">编码名称  例如：gb2312</param>
		/// <returns></returns>
		public string Get(string uri, string refererUri, string encodingName)
		{
			return this.Get(uri, refererUri, encodingName, null);
		}

		/// <summary>
		/// 获取页面html
		/// </summary>
		/// <param name="uri">访问url</param>
		/// <param name="refererUri">来源url</param>
		/// <param name="encodingName">编码名称  例如：gb2312</param>
		/// <param name="webproxy">代理</param>
		/// <returns></returns>
		public string Get(string uri, string refererUri, string encodingName, WebProxy webproxy)
		{
			string empty = string.Empty;
			HttpWebRequest cookieContainer0 = (HttpWebRequest)WebRequest.Create(uri);
			cookieContainer0.ContentType = string.Concat("text/html;charset=", encodingName);
			cookieContainer0.Method = "Get";
			cookieContainer0.CookieContainer = this.cookieContainer_0;
			if (null != webproxy)
			{
				cookieContainer0.Proxy = webproxy;
				if (null != webproxy.Credentials)
				{
					cookieContainer0.UseDefaultCredentials = true;
				}
			}
			if (!string.IsNullOrEmpty(refererUri))
			{
				cookieContainer0.Referer = refererUri;
			}
			HttpWebResponse response = (HttpWebResponse)cookieContainer0.GetResponse();
			try
			{
				Stream responseStream = response.GetResponseStream();
				try
				{
					StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding(encodingName));
					try
					{
						empty = streamReader.ReadToEnd();
					}
					finally
					{
						if (streamReader != null)
						{
							((IDisposable)streamReader).Dispose();
						}
					}
				}
				finally
				{
					if (responseStream != null)
					{
						((IDisposable)responseStream).Dispose();
					}
				}
			}
			finally
			{
				if (response != null)
				{
					((IDisposable)response).Dispose();
				}
			}
			return empty;
		}

		/// <summary>
		/// 获取文件或图片 （验证码）
		/// </summary>
		/// <param name="uri">访问url</param>
		/// <returns></returns>
		public byte[] GetBytes(string uri)
		{
			return this.GetBytes(uri, uri);
		}

		/// <summary>
		/// 获取文件或图片 （验证码）
		/// </summary>
		/// <param name="uri">访问url</param>
		/// <param name="refererUri">来源url</param>
		/// <returns></returns>
		public byte[] GetBytes(string uri, string refererUri)
		{
			return this.GetBytes(uri, refererUri, null);
		}

		/// <summary>
		/// 获取文件或图片 （验证码）
		/// </summary>
		/// <param name="uri">访问url</param>
		/// <param name="refererUri">来源url</param>
		/// <param name="webproxy">Web代理对象</param>
		/// <returns></returns>
		public byte[] GetBytes(string uri, string refererUri, WebProxy webproxy)
		{
			byte[] array;
			byte[] numArray = new byte[0x400];
			Stream stream = this.GetStream(uri, refererUri, webproxy);
			try
			{
				MemoryStream memoryStream = new MemoryStream();
				try
				{
					int num = 0;
					do
					{
						num = stream.Read(numArray, 0, (int)numArray.Length);
						memoryStream.Write(numArray, 0, num);
					}
					while (num != 0);
					array = memoryStream.ToArray();
				}
				finally
				{
					if (memoryStream != null)
					{
						((IDisposable)memoryStream).Dispose();
					}
				}
			}
			finally
			{
				if (stream != null)
				{
					((IDisposable)stream).Dispose();
				}
			}
			return array;
		}

		/// <summary>
		/// 获取文件或图片 （验证码）
		/// </summary>
		/// <param name="uri">访问url</param>
		/// <returns></returns>
		public Stream GetStream(string uri)
		{
			return this.GetStream(uri, uri);
		}

		/// <summary>
		/// 获取文件或图片 （验证码）
		/// </summary>
		/// <param name="uri">访问url</param>
		/// <param name="refererUri">来源url</param>
		/// <returns></returns>
		public Stream GetStream(string uri, string refererUri)
		{
			return this.GetStream(uri, refererUri, null);
		}

		/// <summary>
		/// 获取文件或图片 （验证码）
		/// </summary>
		/// <param name="uri">访问url</param>
		/// <param name="refererUri">来源url</param>
		/// <param name="webproxy">代理</param>
		/// <returns></returns>
		public Stream GetStream(string uri, string refererUri, WebProxy webproxy)
		{
			Stream responseStream;
			HttpWebRequest cookieContainer0 = (HttpWebRequest)WebRequest.Create(uri);
			cookieContainer0.Method = "GET";
			cookieContainer0.CookieContainer = this.cookieContainer_0;
			if (null != webproxy)
			{
				cookieContainer0.Proxy = webproxy;
				if (null != webproxy.Credentials)
				{
					cookieContainer0.UseDefaultCredentials = true;
				}
			}
			if (!string.IsNullOrEmpty(refererUri))
			{
				cookieContainer0.Referer = refererUri;
			}
			HttpWebResponse response = (HttpWebResponse)cookieContainer0.GetResponse();
			try
			{
				responseStream = response.GetResponseStream();
			}
			finally
			{
				if (response != null)
				{
					((IDisposable)response).Dispose();
				}
			}
			return responseStream;
		}

		/// <summary>
		/// POST提交   模拟xp IE7.0     默认GB2312
		/// </summary>
		/// <param name="uri">访问url</param>
		/// <param name="postData">提交的数据</param>
		/// <returns></returns>
		public string Post(string uri, string postData)
		{
			return this.Post(uri, uri, postData, "gb2312");
		}

		/// <summary>
		/// POST提交   模拟xp IE7.0     默认GB2312
		/// </summary>
		/// <param name="uri">访问url</param>
		/// <param name="refererUri">来源url</param>
		/// <param name="postData">提交的数据</param>
		/// <returns></returns>
		public string Post(string uri, string refererUri, string postData)
		{
			return this.Post(uri, refererUri, postData, "gb2312");
		}

		/// <summary>
		/// POST提交    模拟xp IE7.0
		/// </summary>
		/// <param name="uri">访问url</param>
		/// <param name="refererUri">来源url</param>
		/// <param name="postData">提交的数据</param>
		/// <param name="encodingName">编码名称  例如：gb2312</param>
		/// <returns></returns>
		public string Post(string uri, string refererUri, string postData, string encodingName)
		{
			return this.Post(uri, refererUri, postData, encodingName, null);
		}

		/// <summary>
		/// POST提交    模拟xp IE7.0
		/// </summary>
		/// <param name="uri">访问url</param>
		/// <param name="refererUri">来源url</param>
		/// <param name="postData">提交的数据</param>
		/// <param name="encodingName">编码名称  例如：gb2312</param>
		/// <param name="webproxy">代理</param>
		/// <returns></returns>
		public string Post(string uri, string refererUri, string postData, string encodingName, WebProxy webproxy)
		{
			string empty = string.Empty;
			HttpWebRequest cookieContainer0 = (HttpWebRequest)WebRequest.Create(uri);
			cookieContainer0.Accept = "*/*";
			cookieContainer0.Headers.Add("Accept-Language", "zh-cn");
			cookieContainer0.ContentType = "application/x-www-form-urlencoded";
			cookieContainer0.Headers.Add("UA-CPU", "x86");
			cookieContainer0.Headers.Add("Accept-Encoding", "gzip, deflate");
			cookieContainer0.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.0.04506.30)";
			cookieContainer0.Headers.Add("Cache-Control", "no-cache");
			cookieContainer0.CookieContainer = this.cookieContainer_0;
			cookieContainer0.Method = "POST";
			if (!string.IsNullOrEmpty(refererUri))
			{
				cookieContainer0.Referer = refererUri;
			}
			if (null != webproxy)
			{
				cookieContainer0.Proxy = webproxy;
				if (null != webproxy.Credentials)
				{
					cookieContainer0.UseDefaultCredentials = true;
				}
			}
			Encoding encoding = Encoding.GetEncoding(encodingName);
			byte[] bytes = encoding.GetBytes(postData);
			cookieContainer0.ContentLength = (long)((int)bytes.Length);
			StringBuilder stringBuilder = new StringBuilder();
			if (this.cookieContainer_0 != null)
			{
				foreach (Cookie cooky in this.cookieContainer_0.GetCookies(cookieContainer0.RequestUri))
				{
					stringBuilder.Append(string.Concat(cooky, ";"));
				}
			}
			if (stringBuilder.Length > 0)
			{
				long ticks = DateTime.UtcNow.Ticks;
				DateTime dateTime = new DateTime(0x7b2, 1, 1);
				long num = ticks - dateTime.Ticks;
				num = num / 0x2710L;
				cookieContainer0.Headers.Add("Cookie", string.Concat("cookLastGetMsgTime=", num.ToString(), "; ", stringBuilder.ToString()));
			}
			Stream requestStream = cookieContainer0.GetRequestStream();
			try
			{
				requestStream.Write(bytes, 0, (int)bytes.Length);
			}
			finally
			{
				if (requestStream != null)
				{
					((IDisposable)requestStream).Dispose();
				}
			}
			HttpWebResponse response = (HttpWebResponse)cookieContainer0.GetResponse();
			try
			{
				Stream responseStream = response.GetResponseStream();
				try
				{
					StreamReader streamReader = new StreamReader(responseStream, encoding);
					try
					{
						empty = streamReader.ReadToEnd();
					}
					finally
					{
						if (streamReader != null)
						{
							((IDisposable)streamReader).Dispose();
						}
					}
				}
				finally
				{
					if (responseStream != null)
					{
						((IDisposable)responseStream).Dispose();
					}
				}
			}
			finally
			{
				if (response != null)
				{
					((IDisposable)response).Dispose();
				}
			}
			return empty;
		}
	}
}